package priv.mill.db;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;

public abstract class AbstrctService<T> implements Service<T> {

	private static Logger logger = Logger.getLogger(AbstrctService.class);
	private Class<T> clzz;
	private String tableName;
	private SqlWorker sqlWorker;

	public AbstrctService(Class<T> clazz) {

		this.clzz = clazz;
		this.tableName = NameUtils.toUnder(clazz.getSimpleName());
		logger.info(clazz.getName() + "生成表名" + tableName);
		sqlWorker = SqlWorker.getInstance(tableName);
	}

	public AbstrctService(Class<T> clazz, String tableName) {
		this.clzz = clazz;
		this.tableName = tableName;
	}

	@Override
	public T findOne(String sql, Object... args) throws SQLException, Exception {
		return DBUtils.queryOne(clzz, sql, args);
	}

	@Override
	public T findById(int id) throws Exception {
		String sql = sqlWorker.findById();
		return findOne(sql, id);
	}

	public static void main(String[] args) throws SQLException, Exception {
		List<Map<String, Object>> query = DBUtils.query("show index from car_info");
		System.out.println(query);
	}

	@Override
	public List<T> findByPage(Integer pageNum, Integer pageSize) throws SQLException, Exception {
		String sql = sqlWorker.findByPage();
		return find(sql,(pageNum-1)*pageSize,pageSize);
	}

	@Override
	public List<T> find(String sql, Object... args) throws SQLException, Exception {
		return DBUtils.query(clzz, sql, args);
	}

	@Override
	public Integer insert(T obj) throws SQLException, Exception {
		Map<String, String> describe = BeanUtils.describe(obj);
		logger.info("参数"+describe.toString());
		return sqlWorker.insert(describe);
	}

	@Override
	public Integer update(T obj) throws SQLException, Exception {
		Map<String, String> describe = BeanUtils.describe(obj);
		int id = sqlWorker.getPrimary(describe);
		T findById = findById(id);
		for (Entry<String, String> item : describe.entrySet()) {
			if(item.getValue()!=null)
				BeanUtils.setProperty(findById, item.getKey(), item.getValue());
		}
		logger.info(findById);
		Map<String, String> describe2 = BeanUtils.describe(findById);
		return sqlWorker.update(describe2);
	}

	@Override
	public Integer delete(int id) throws SQLException, Exception {
		String sql= sqlWorker.delete();
		return DBUtils.update(sql, id);
	}
	
	

}
